package 开始的算法算法入门8月.双指针;
// https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
public class 两数之和输入有序数组0814 {
    class Solution {
        //双指针
        //  public int[] twoSum(int[] numbers, int target) {
        //     int low = 0, high = numbers.length - 1;
        //     while (low < high) {
        //         int sum = numbers[low] + numbers[high];
        //         if (sum == target) {
        //             return new int[]{low + 1, high + 1};
        //         } else if (sum < target) {
        //             ++low;
        //         } else {
        //             --high;
        //         }
        //     }
        //     return new int[]{-1, -1};
        // }

        //二分法
        public int[] twoSum(int[] numbers, int target) {
            for (int i = 0; i < numbers.length; ++i) {
                int low = i + 1, high = numbers.length - 1;
                while (low <= high) {
                    int mid = (high - low) / 2 + low;
                    if (numbers[mid] == target - numbers[i]) {
                        return new int[]{i + 1, mid + 1};
                    } else if (numbers[mid] > target - numbers[i]) {
                        high = mid - 1;
                    } else {
                        low = mid + 1;
                    }
                }
            }
            return new int[]{-1, -1};
        }

    }
}
